package com.iot.manager.ui.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import com.iot.manager.R;
import com.iot.manager.data.models.DeviceConfig;
import com.iot.manager.network.RetrofitClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import okhttp3.ResponseBody;

import org.json.JSONObject;

public class DeviceControlDialog extends Dialog {
    private final String deviceId;
    private TextInputEditText etSamplingInterval;
    private TextInputEditText etUploadInterval;
    private TextInputEditText etTempLow;
    private TextInputEditText etTempHigh;
    private TextInputEditText etHumidityLow;
    private TextInputEditText etHumidityHigh;
    private MaterialButton btnRestart;
    private MaterialButton btnSave;
    private MaterialButton btnCancel;

    public DeviceControlDialog(@NonNull Context context, String deviceId) {
        super(context);
        this.deviceId = deviceId;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_device_control, null);
        setContentView(view);

        initViews(view);
        loadDeviceConfig();
        setupListeners();
    }

    private void initViews(View view) {
        etSamplingInterval = view.findViewById(R.id.etSamplingInterval);
        etUploadInterval = view.findViewById(R.id.etUploadInterval);
        etTempLow = view.findViewById(R.id.etTempLow);
        etTempHigh = view.findViewById(R.id.etTempHigh);
        etHumidityLow = view.findViewById(R.id.etHumidityLow);
        etHumidityHigh = view.findViewById(R.id.etHumidityHigh);
        btnRestart = view.findViewById(R.id.btnRestart);
        btnSave = view.findViewById(R.id.btnSave);
        btnCancel = view.findViewById(R.id.btnCancel);
    }

    private void loadDeviceConfig() {
        RetrofitClient.getInstance().getApiService().getDeviceConfig(deviceId)
            .enqueue(new Callback<DeviceConfig>() {
                @Override
                public void onResponse(Call<DeviceConfig> call, Response<DeviceConfig> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        DeviceConfig config = response.body();
                        updateUIWithConfig(config);
                    } else {
                        Toast.makeText(getContext(), "加载配置失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<DeviceConfig> call, Throwable t) {
                    Toast.makeText(getContext(), "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
    }

    private void updateUIWithConfig(DeviceConfig config) {
        etSamplingInterval.setText(String.valueOf(config.getSamplingInterval()));
        etUploadInterval.setText(String.valueOf(config.getUploadInterval()));
        
        if (config.getAlarmThresholds() != null) {
            if (config.getAlarmThresholds().getTemperature() != null) {
                etTempLow.setText(String.valueOf(config.getAlarmThresholds().getTemperature().getLow()));
                etTempHigh.setText(String.valueOf(config.getAlarmThresholds().getTemperature().getHigh()));
            }
            if (config.getAlarmThresholds().getHumidity() != null) {
                etHumidityLow.setText(String.valueOf(config.getAlarmThresholds().getHumidity().getLow()));
                etHumidityHigh.setText(String.valueOf(config.getAlarmThresholds().getHumidity().getHigh()));
            }
        }
    }

    private void setupListeners() {
        btnRestart.setOnClickListener(v -> restartDevice());
        btnSave.setOnClickListener(v -> saveConfig());
        btnCancel.setOnClickListener(v -> dismiss());
    }

    private void restartDevice() {
        RetrofitClient.getInstance().getApiService().sendCommand(deviceId, "restart", "{}")
            .enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        Toast.makeText(getContext(), "设备重启命令已发送", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getContext(), "发送重启命令失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Toast.makeText(getContext(), "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
    }

    private void saveConfig() {
        try {
            DeviceConfig config = new DeviceConfig();
            config.setSamplingInterval(Integer.parseInt(etSamplingInterval.getText().toString()));
            config.setUploadInterval(Integer.parseInt(etUploadInterval.getText().toString()));

            DeviceConfig.AlarmThresholds thresholds = new DeviceConfig.AlarmThresholds();
            DeviceConfig.TemperatureThresholds tempThresholds = new DeviceConfig.TemperatureThresholds();
            tempThresholds.setLow(Double.parseDouble(etTempLow.getText().toString()));
            tempThresholds.setHigh(Double.parseDouble(etTempHigh.getText().toString()));
            thresholds.setTemperature(tempThresholds);

            DeviceConfig.HumidityThresholds humidityThresholds = new DeviceConfig.HumidityThresholds();
            humidityThresholds.setLow(Double.parseDouble(etHumidityLow.getText().toString()));
            humidityThresholds.setHigh(Double.parseDouble(etHumidityHigh.getText().toString()));
            thresholds.setHumidity(humidityThresholds);

            config.setAlarmThresholds(thresholds);

            RetrofitClient.getInstance().getApiService().updateDeviceConfig(deviceId, config)
                .enqueue(new Callback<DeviceConfig>() {
                    @Override
                    public void onResponse(Call<DeviceConfig> call, Response<DeviceConfig> response) {
                        if (response.isSuccessful()) {
                            Toast.makeText(getContext(), "配置更新成功", Toast.LENGTH_SHORT).show();
                            dismiss();
                        } else {
                            Toast.makeText(getContext(), "配置更新失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<DeviceConfig> call, Throwable t) {
                        Toast.makeText(getContext(), "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
        } catch (NumberFormatException e) {
            Toast.makeText(getContext(), "请输入有效的数值", Toast.LENGTH_SHORT).show();
        }
    }
} 